package com.ysncms.ext;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.repackaged.org.json.JSONObject;

public class YSNAuthServlet implements Filter {
	
	public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain)
	throws IOException {
		try {
			String path = ((HttpServletRequest) req).getRequestURI();
			if (path.startsWith("/ysnAuth")) {
				authAndRedirect(req, res);
			} else {
				 // Just continue chain.
				chain.doFilter(req, res);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void authAndRedirect(ServletRequest req, ServletResponse res) {
			
		String ysn = Constants.APP_HOST_NAME;
		String ynscms = Constants.CMS_HOST_NAME;
		try {
			String email = req.getParameter("email");
			String password = req.getParameter("password");
			
			email = (email != null && !email.isEmpty())? email : ""; 
			password = (password != null && !password.isEmpty())? password : "";
			
			JSONObject json = new JSONObject();
			json.put("username", email);
			json.put("password", password);
			
			URL url = new URL(ysn+"tnvrs/userservice/login/checkUser/");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			
			conn.setReadTimeout(60 * 1000);
			conn.setConnectTimeout(60 * 1000);
			
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches (false);
			
			conn.setRequestMethod("POST"); 
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
			conn.setRequestProperty("charset", "utf-8");
			conn.setRequestProperty("Content-Length", "" + Integer.toString(json.toString().getBytes().length));
			
			DataOutputStream wr = new DataOutputStream(conn.getOutputStream ());
			wr.writeBytes(json.toString());
			wr.flush();
			wr.close();
			
			BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
			String output = br.readLine();
			if (output != null) {
				if(output.startsWith("Error")){
					res.getWriter().write("<script> " +
												"window.location.href = '"+ynscms+"?auth=fail';  " +
										   "</script>");
				} else {
					((HttpServletResponse) res).sendRedirect(((HttpServletResponse) res).encodeRedirectURL(ysn+output) );
				}
			} else {
				((HttpServletResponse) res).sendRedirect(((HttpServletResponse) res).encodeRedirectURL(ynscms) );
			}
			conn.disconnect();
		} catch(Exception ste){
			System.err.println(ste);
			try {
				res.getWriter().write("<script> " +
						"window.location.href = '"+ynscms+"?auth=fail';  " +
				   "</script>");
			} catch (IOException e) {
				System.err.println(e);
			}
		}
	}

	@Override
	public void destroy() {
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}
	
	
}
